const Koa = require("koa")
const KoaStaticCache = require("koa-static-cache")
const KoaRouter = require("@koa/router")
const Nunjucks = require("nunjucks")
const Mysql = require("mysql2")
const KoaBody = require("koa-body")

// 创建数据库连接
const connection = Mysql.createConnection({
  host: "localhost",
  user: "root",
  password: 'bsc123321',
  database: "kkb"
})

const app = new Koa();

Nunjucks.configure('./template', {
  noCache: true,// 关闭缓存
  watch: true,
})

// 1. 使用静态资源中间件
app.use(KoaStaticCache('./public', {
  prefix: "/public",
  dynamic: true,
  gzip: true,
}))

// 2. 使用路由处理动态资源
const router = new KoaRouter();

// 数据处理配置
let uploadKoaBodyOptions = {
  // 能解析multipart格式提交过来的数据
  multipart: true,
  // 设置处理二进制
  formidable: {
    uploadDir: "./attachments",// 上传文件保存路径
    keepExtensions: true,// 是否保存上传的后缀
  }
}

// 首页
router.get("/", getCategories, async ctx => {
  ctx.body = Nunjucks.render("index.html", {
    categories: ctx.state.categories
  })
})

// 注册页
router.get("/register", getCategories, async ctx => {
  ctx.body = Nunjucks.render('register.html', {
    categories: ctx.state.categories
  })
})

// 处理注册
router.post("/register", KoaBody(), async ctx => {
  let {name, password, rePassword} = ctx.request.body;
  if (name && password && rePassword) {
    if (password === rePassword) {
      let res = await query("insert into `users` (`name`,`password`) values (?,?)", [name, password]);
      ctx.body = "注册成功"
    } else {
      ctx.body = "两次密码输入不一致"
    }
  } else {
    ctx.body = "缺少字段"
  }
})

// 登录页
router.get("/login", getCategories, ctx => {
  ctx.body = Nunjucks.render('login.html', {
    categories: ctx.state.categories
  })
})

// 处理登录
router.post("/login", KoaBody(), async ctx => {
  console.log(ctx.request.body)
  let {name, password} = ctx.request.body;
  if (name && password) {
    let [user] = await query('select * from `users` where name=? and password=?', [name, password])
    if (user) {
      ctx.body = "登录成功"
    } else {
      ctx.body = "用户名或密码错误"
    }
  } else {
    ctx.body = "请输入用户名/密码"
  }
})

// 上传页面
router.get("/upload", getCategories, async ctx => {
  ctx.body = Nunjucks.render('upload.html', {
    categories: ctx.state.categories
  })
})

// 上传处理
router.post("/upload", KoaBody(uploadKoaBodyOptions), async ctx => {
  // 获取文件对象
  let file = ctx.request.files.cover;
  // 获取文件名
  let lastIndexPoint = file.path.lastIndexOf('/')
  let fileName = file.path.substring(lastIndexPoint + 1)
  // 获取文件类型
  let fileType = file.type;
  // 获取文件大小
  let size = file.size;

  // 存入数据库
  let res = await query('insert into `attachments` (`filename`,`type`,`size`) values(?,?,?)', [
    fileName, fileType, size
  ])
  console.log(res)
  if (res.affectedRows) {
    ctx.body = '上传成功'
  } else {
    ctx.body = '上传失败'
  }
})

app.use(router.routes())

// 3. 监听端口
app.listen(8888, () => {
  console.log("启动成功Nodejs04:http://localhost:8888")
})

// 创建分类列表中间件
async function getCategories(ctx, next) {
  ctx.state.categories = await query('select * from categories')
  next();
}

// 创建sql执行函数
function query(sql, data) {
  return new Promise((resolve, reject) => {
    connection.query(sql, data, function (err, ...data) {
      if (err) {
        reject(err)
      } else {
        resolve(...data);
      }
    })
  })
}